// pages/map/map.ts
const chooseLocation = requirePlugin('chooseLocation');
const QQMapWX = require('../../lib/qqmap-wx-jssdk');
const qqmapsdk = new QQMapWX({
    key: 'RVPBZ-X7RKI-2YGGS-UMLIW-JANZK-3TBWZ'
});
const citySelector = requirePlugin('citySelector');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        selectorVisible: false,
        selectedProvince: null,
        selectedCity: null,
        selectedCity1: null,
        words: ['公交车站', '餐饮', '医院', '学校', '景点', '休闲', '娱乐', '电影'],
        word: '公交车站',
        address: '湖南省株洲市中心广场',
        markers: [],
        latitude: '',
        longitude: '',
        windowHeight: '100px',
        hotCitys: ['北京', '上海', '深圳']
    },
    handleInput: function (e) {
        console.log(e);
        // 将输入框的值赋给 data 中的 inputVal
        this.setData({
            inputVal: e.detail.value
        });
    },
    luxian() {
        let plugin = requirePlugin('routePlan');
        let key = 'RVPBZ-X7RKI-2YGGS-UMLIW-JANZK-3TBWZ';  // 使用在腾讯位置服务申请的key
        let referer = '路线';   // 调用插件的app的名称
        let endPoint = JSON.stringify({  // 终点
            'name': '北京西站',
            'latitude': 39.894806,
            'longitude': 116.321592
        });
        wx.navigateTo({
            url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + endPoint
        });
    },
    getCurrentLocation: function () {
        let that = this;
        // 获取当前位置的经纬度
        wx.getLocation({
            type: 'gcj02', // 返回可用于 wx.openLocation 的坐标
            success: function (res) {
                const latitude = res.latitude;
                const longitude = res.longitude;
                // 调用腾讯地图 SDK 的逆地理编码方法，将经纬度转换为位置信息
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: latitude,
                        longitude: longitude
                    },
                    success: function (addressRes) {
                        const locationName = addressRes.result.address;
                        // 更新页面数据
                        that.setData({
                            address: locationName,
                            latitude: latitude,
                            longitude: longitude
                        });
                    },
                    fail: function (error) {
                        console.error(error);
                    }
                });
            },
            fail: function (error) {
                console.error(error);
            }
        });
    },
    onxuandian1() {
        var inputValue = this.data.address;
        const hotCitysString = this.data.hotCitys;
        wx.navigateTo({
            url: `plugin://citySelector/index?key=RVPBZ-X7RKI-2YGGS-UMLIW-JANZK-3TBWZ&referer=${inputValue}&hotCitys=${hotCitysString}`,
        })
    },
    showSelector() {
        this.setData({
            selectorVisible: true,
        });
    },

    // 当用户选择了组件中的城市之后的回调函数
    onSelectCity(e: any) {
        const { province, city } = e.detail;
        this.setData({
            selectedProvince: province,
            selectedCity: city,
        });
    },
    onwords(e: any) {
        this.setData({
            word: this.data.words[e.currentTarget.dataset.i]
        })
        this.nearby_search(this.data.latitude + "," + this.data.longitude);
    },
    formSubmit() {
        var _this = this;
        // 调用地址解析接口
        qqmapsdk.geocoder({
            // 获取表单传入地址
            address: _this.data.address,
            success: function (res) { // 成功后的回调
                var res = res.result;
                let location = res.location.lat + ',' + res.location.lng;
                _this.setData({
                    latitude: res.location.lat,
                    longitude: res.location.lng,
                });
                _this.nearby_search(location);
            },
            fail: function (error) {
                console.error(error);
            },
            complete: function (res) {
                console.log(res);
            }
        });
    },

    formatDistance(distanceInMeters: any) {
        if (distanceInMeters >= 1000) {
            // 将距离转换为公里并保留一位小数
            return (distanceInMeters / 1000).toFixed(1) + ' km';
        } else {
            return distanceInMeters + ' m';
        }
    },

    nearby_search: function (location: any) {
        var _this = this;
        // 调用接口
        qqmapsdk.search({
            keyword: _this.data.word,  //搜索关键词
            location: location,  //设置周边搜索中心点
            success: function (res: any) { //搜索成功后的回调
                var mks = [];
                for (var i = 0; i < res.data.length; i++) {
                    let distance = res.data[i]._distance;
                    let formattedDistance = _this.formatDistance(distance);
                    mks.push({ // 获取返回结果，放到mks数组中
                        title: res.data[i].title,
                        id: res.data[i].id,
                        latitude: res.data[i].location.lat,
                        longitude: res.data[i].location.lng,
                        iconPath: "https://t10.baidu.com/it/u=3821602422,186257727&fm=30&app=106&f=PNG?w=640&h=640&s=CF85326241EEB6BA394BDFAC03005069", //图标路径
                        width: 20,
                        height: 20,
                        _distance: distance,
                        callout: {
                            content: res.data[i].title + "\n" + "距离您 " + formattedDistance,
                            color: '#404040',
                            bgColor: '#ffffff',
                            borderWidth: 1,
                            borderColor: '#8a8a8a',
                            fontSize: 14,
                            padding: 10,
                            borderRadius: 10,
                            display: 'ALWAYS'
                        }
                    });
                }
                _this.setData({ //设置markers属性，将搜索结果显示在地图中
                    markers: mks
                });
            },
            fail: function (res: any) {
                console.log(res);
            },
            complete: function (res: any) {
                console.log(res);
            }
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function () {
        this.getCurrentLocation();
        this.formSubmit();
        var windowHeight = wx.getSystemInfoSync().windowHeight;
        this.setData({
            windowHeight: (windowHeight - 44) + 'px'
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        const selectedCity = citySelector.getCity(); // 选择城市后返回城市信息对象，若未选择返回null
        const selectedCity1 = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
        console.log(selectedCity1);
        if (selectedCity1 != null) {
            this.setData({
                selectedCity1: selectedCity1,
                address: selectedCity1.name,
                latitude: selectedCity1.latitude,
                longitude: selectedCity1.longitude
            })
            this.formSubmit();
        }
        if (selectedCity != null) {
            this.setData({
                selectedCity: selectedCity,
                address: selectedCity.name,
                latitude: selectedCity.latitude,
                longitude: selectedCity.longitude
            })
            this.formSubmit();
        }
        console.log(selectedCity);

    },
    onxuandian() {
        const location = JSON.stringify({
            latitude: 39.89631551,
            longitude: 116.323459711
        });
        const category = '生活服务,娱乐休闲';
        wx.navigateTo({
            url: `plugin://chooseLocation/index?key=RVPBZ-X7RKI-2YGGS-UMLIW-JANZK-3TBWZ&referer=株洲科泰&location=${location}&category=${category}`
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        citySelector.clearCity();
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})